#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python常用模块库 
@File ：多进程读写.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/2/20 上午1:13 
"""

import multiprocessing

from shared_memory import SharedMemory


def writer_process(memory_name: str, memory_size: int):
	"""写入数据的进程"""
	with SharedMemory(memory_name, memory_size, create=True) as shm:
		data = [1, 2, 3, 4, 5]
		print(f"Writer: Writing data {data}")
		shm.write(data)


def reader_process(memory_name: str, memory_size: int):
	"""读取数据的进程"""
	with SharedMemory(memory_name, memory_size, create=False) as shm:
		result = shm.read()
		print(f"Reader: Read data {result}")


if __name__ == "__main__":
	memory_name = "/shm_test_multi"
	memory_size = 1024  # 1KB

	# 创建进程
	writer = multiprocessing.Process(target=writer_process, args=(memory_name, memory_size))
	reader = multiprocessing.Process(target=reader_process, args=(memory_name, memory_size))

	# 启动进程
	writer.start()
	writer.join()  # 确保写入完成
	reader.start()
	reader.join()

	# 清理共享内存
	shm = SharedMemory(memory_name, memory_size, create=False)
	shm.unlink()
